package mushystuff.dtb.web.controller.admin;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import mushystuff.dtb.core.model.Product;
import mushystuff.dtb.core.service.ProductService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

@Controller
@SessionAttributes("product")
public class ProductModify {

    @Resource
    protected ProductService productService;

    @RequestMapping(value = "/productModify.do", method = RequestMethod.GET)
    public String selectProduct(
            @RequestParam(value = "productId", required = false) Long productId,
            ModelMap model, HttpSession session) {
        if (productId != null) {
            model.addAttribute("product", productService.getProduct(productId));
        } else {
            model.addAttribute("product", new Product());
        }
        model.addAttribute("productSelectorList", productService
                .getAllActiveProducts());
        return "dtb.product.modify";
    }

    @RequestMapping(value = "/productModify.do", method = RequestMethod.POST)
    public String viewProducts(@ModelAttribute("product") Product product,
            SessionStatus status) {
        productService.createUpdateProduct(product);
        status.setComplete();
        return "redirect:/productsAdmin.do";
    }

}
